import React, { useEffect, useRef } from "react";
import styled from 'styled-components'
import { debounce, downloadDocument } from '@/util/util'
import { Modal, Message } from "@arco-design/web-react";
import * as echarts from "echarts";
import { EChartsType } from "echarts";

interface IOptions {
    showLegend?: boolean;
    yLabel?: string;
    xLabel?: string;
}

export interface IChartData {
    name?: string;
    type?: string;
    smooth?: boolean;
    areaStyle?: any;
    data: any;
    options?: IOptions;
};

export interface ILineChartsShown {
    id: string;
    style?: Record<string, string>;
    data?: IChartData[];
    area?: string;
}
type EChartsOption = echarts.EChartsOption;

const Wrapper = styled.div`
    position: relative;
    width: 100%;
    height: 100%;
`;

const LineChartsShown = (props: ILineChartsShown) => {

    const { id, style, data, area } = props;
    const chartRef = useRef<EChartsType | null>();
    
    const xArr: number[] = []
    const len = (data?.length && data[0]?.data?.length) || 60;
    
    for(let i = 0; i < len; i++) {
        xArr.push(i + 1)
    }
    
    const fixedOptions: EChartsOption = {
        tooltip: {
            trigger: 'axis',
            position: function (pt) {
                return [pt[0], '10%'];
            }
        },
        grid: {
            top: "40px",
            left: "30px",
            right: "35px",
            bottom: "30px",
        },
        xAxis: {
            name: (data?.length && data[0]?.options?.xLabel) || '日',
            type: 'category',
            data: xArr,
            nameTextStyle: {
                fontSize: 16,
            },
        },
        legend: {
            show: true,
            icon: 'pin',
            textStyle: {
                fontSize: 16,
                color: 'white'
            }
        },
        yAxis: {
            name: (data?.length && data[0]?.options?.yLabel) || '异常值',
            type: 'value',
            splitLine: {
                lineStyle: {
                    type: 'dotted',
                }
            },
            nameTextStyle: {
                fontSize: 16,
            },
            max: function (value) {
                return Math.floor(value.max + 0.5);
            },
            min: function (value) {
                return Math.floor(value.min);
            },
        },
    }

    const option: EChartsOption = {
        ...fixedOptions,
        series: data || new Array(7).fill(0)
    };

    useEffect(() => {

        
        const wrapper = document.querySelector(`#wrapper_${id}`)!;
        const chartDom = document.getElementById(`charts_${id}`)!;
        chartRef.current = echarts.init(chartDom, '', { renderer: 'svg' });

        const debounceResize = debounce(chartRef.current.resize, 0);

        const obCallback = () => {
            debounceResize();
        }

        if (data) option && chartRef.current?.setOption(option);
        
        // 双击下载
        const doubleClick = () => {
            const svg = chartDom?.firstChild?.firstChild;
            Modal.confirm({
                title: '确认',
                content: '此操作将会下载图表的SVG图, 是否确定下载',
                okButtonProps: {
                    status: 'danger',
                },
                onOk: () => {
                    return new Promise((resolve) => {
                        downloadDocument((svg as HTMLElement)?.outerHTML, `${id}.svg`)
                        resolve(svg);
                    }).catch((e) => {
                        Message.error({
                        content: '下载失败',
                        });
                    });
                },
            });
        }
        
        const observer = new ResizeObserver(obCallback)

        observer.observe(wrapper)
        chartDom?.addEventListener("dblclick", doubleClick);
        
        return () => {
            observer.unobserve(wrapper);
            observer.disconnect();
            chartDom?.removeEventListener("dblclick", doubleClick);
        }
    }, [ data ])

    useEffect(() => {
        const prevOption = chartRef.current?.getOption()
        if (prevOption) {
            for(let i = 0; i < (prevOption as any).series?.length; i++) {
                (prevOption as any).series[i].data = (prevOption as any).series[i].data?.map((v) => v);
            }
            chartRef.current?.setOption(prevOption, true)
        }
    }, [ area, chartRef.current ])

    return (
        <Wrapper style={{...(style || {})}} id={`wrapper_${id}`}>
            <div style={{ width: '100%', height: style?.height ?? '200px' }} id={`charts_${id}`}></div>
        </Wrapper>
    )
}


export default LineChartsShown;